#!/usr/bin/env python

import os, sys
import logging
import yaml

import mei

from mei import application, plugin, theme, datafiles
from mei.gui import menu 
from mei.version import *

# Load global or user config.
config = None
for config_file in ['./pymei.config', '~/.pymei/config', '/etc/pymei.config']:
    config_file = os.path.expanduser(config_file)
    if os.path.isfile(config_file):
        config = yaml.load(open(config_file))
        print "Using file '%s' for config." % config_file
        break

if config.get('debug'):
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

searchpath = ['.', os.path.expanduser('~/.pymei'), '/usr/share/pymei']
theme.set_searchpath(searchpath)
datafiles.set_searchpath(searchpath)

# We can't start without a config! :)
if config is None:
    logging.fatal('Could not find any config file!')
    sys.exit(1)

# Load global & user plugins.
for plugdir in [os.path.join(os.path.dirname(mei.__file__), 'plugins'), os.path.expanduser('~/.pymei/plugins')]:
    logging.debug("Loading plugins from dir '%s'" % plugdir)
    plugin.load_plugins(plugdir)

logging.info('Starting %s v%s' % (APP_NAME, APP_VERSION))

# Start mei.application with Menu as the first screen.
current_app = application.Application(menu.Menu, config)

# If we're running in debug mode, start the debug server.
if config.get('debug'):
    # Make some neat aliases for the debug server.
    _ = a = app = current_app
    from mei import debugserver
    (debugthread, debugsvr) = debugserver.spawn(locals())

while current_app.run():
    pass
current_app.quit()
